/*
 * =====================================================================================
 *
 *       Filename:  cl_timer.hxx
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  10/09/2010 12:00:29 AM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Ken Chen (Ziliang), zlchen.ken@gmail.com
 *        Company:  EMC
 *
 * =====================================================================================
 */

#ifndef _CL_TIMER_HXX_
#define _CL_TIMER_HXX_

#include <memory>
#include <functional>
#include "cl_timestamp.hxx"
#include "cl_id.hxx"
#include "cl_callback.hxx"

namespace neo
{
class CLTimer
{
public:
  static std::shared_ptr<CLTimer> create(const CLCallbackFunctor& cb, 
			                                   const CLTimestamp& when, 
																				 int msecInterval); 
	void restart(const CLTimestamp& when);
	bool isExpired(void) const; 
	bool isRepeated(void) const; 
  const CLTimestamp expirationTime(void) const;
  void exec(void) const;
  const CLId identity(void) const;

private:
	CLTimer(const CLCallbackFunctor& cb, const CLTimestamp& when, int msecInterval);

private:
  CLId m_id;
  CLTimestamp m_expiration;
	int m_msecInterval;
  CLCallbackFunctor m_callback;
};

class TimerLaterThan: public std::unary_function<std::shared_ptr<CLTimer>, bool>
{
public:
  TimerLaterThan(const CLTimestamp& ts)
    : m_timeStamp(ts)
  {
  }

  bool operator()(const std::shared_ptr<CLTimer>& aTimer)
  {
     return m_timeStamp < aTimer->expirationTime();
  }

private:
  CLTimestamp m_timeStamp;
};

/// Helper functors for CLTimer
class TimerEarlierThan: public std::unary_function<std::shared_ptr<CLTimer>, bool>
{
public:
  TimerEarlierThan(const CLTimestamp& ts)
    : m_timeStamp(ts)
  {
  }

  bool operator()(const std::shared_ptr<CLTimer>& aTimer)
  {
     return m_timeStamp > aTimer->expirationTime();
  }

private:
  CLTimestamp m_timeStamp;
};

class TimerIdEqualTo: public std::unary_function<std::shared_ptr<CLTimer>, bool>
{
public:
  TimerIdEqualTo(const CLId& timerId)
    : m_timerId(timerId)
  {
  }

  bool operator()(const std::shared_ptr<CLTimer>& aTimer)
  {
     return m_timerId == aTimer->identity();
  }

private:
  CLId m_timerId;
};

} // neo

#endif //_CL_TIMER_HXX_

